the code below will return the lasted known location of the phone using the Android platform.

Get Phone location in Android

import 	android.location.LocationManager;

public double[] getGPSLocation() {
       double[] LatLong = new double[2];
        LocationManager _locationmanager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);  
        List<String> _providers = _locationmanager .getProviders(true);

        Location _location = null;
        
        for (int i = _providers.size()-1; i>=0; i--) {
                _location = _locationmanager.getLastKnownLocation(providers.get(i));
                if (_location != null) break;
        }
        
     
        if (_location != null) {
                LatLong[0] = _location.getLatitude();
                LatLong[1] = _location.getLongitude();
        }
        return _location;
}

Code Explanation

After initializing the two variables needed for program, we create a loop that goes thought the providers array, starting from the last element, as we want to get the latest known location. The loop will exit once the location found is not null.

Then we create another array and store the latitude and longitude properties of the location variable into it.

Related Articles

Last modified: March 27, 2019